package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.commom.exception.CustException;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author by jojo
 * @Date 2022/2/27
 * @Description
 */
@Service
@Slf4j
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Override
    public ResponseResult login(WmUserDTO dto) {
        //校验用户名和密码
        String name = dto.getName();
        String password = dto.getPassword();
        if (StringUtils.isBlank(name)||StringUtils.isBlank(password)) {
            log.error("用户名或者密码错误 {}，{}",name,password);
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或者密码错误");
        }
        //根据用户名查该用户是否存在
        LambdaQueryWrapper<WmUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WmUser::getName,name);
        WmUser wmUser = this.getOne(wrapper);
        if (wmUser==null) {
            log.error("该用户不存在 {}",name);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该用户不存在！！！");
        }
        //判断状态码是否正常 9为正常
        if (!WemediaConstants.WMUSER_STATUS_ALLOW.equals(wmUser.getStatus())) {
            log.error("状态码异常 {}",wmUser.getStatus());
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"状态码异常");
        }
        //判断密码是否错误
        String salt = wmUser.getSalt();
        String loginPwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!loginPwd.equals(wmUser.getPassword())) {
            log.error("密码错误，{}",password);
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //修改登录时间
        wmUser.setLoginTime(new Date());
        updateById(wmUser);
        //颁发token
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        //封装返回
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(wmUser,wmUserVO);
        Map map= new HashMap<>();
        map.put("token",token);
        map.put("user",wmUserVO);
        return ResponseResult.okResult(map);
    }
}
